import axios from 'axios'
import { put, takeEvery } from 'redux-saga/effects'
import { API } from '../../config'
import {
  SignupAction,
  SIGNUP,
  SIGNUP_SUCCESS,
  SIGNUP_FAIL,
  SigninAction,
  SIGNIN,
  SIGNIN_SUCCESS,
  SIGNIN_FAIL,
} from '../actions/auth'

function* handleSignup(action: SignupAction) {
  try {
    yield axios.post(`${API}/signup`, action.payload)
    yield put({ type: SIGNUP_SUCCESS })
  } catch (error) {
    yield put({ type: SIGNUP_FAIL, message: error.response.data.error })
  }
}

function* handleSignin(action: SigninAction) {
  try {
    let response: { data: any } = yield axios.post(
      `${API}/signin`,
      action.payload
    )
    localStorage.setItem('token', JSON.stringify(response.data))
    yield put({ type: SIGNIN_SUCCESS })
  } catch (error) {
    yield put({ type: SIGNIN_FAIL, message: error.response.data.error })
  }
}

export default function* authSaga() {
  yield takeEvery(SIGNUP, handleSignup)
  yield takeEvery(SIGNIN, handleSignin)
}
